package com.example.flutter_vpn

import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.ParcelFileDescriptor
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.io.File
import java.io.FileOutputStream
import java.nio.charset.Charset

/**
 * VPN 插件 - Android 平台实现
 * 提供与 V2Ray/Xray 核心的交互接口
 */
class VpnPlugin : FlutterPlugin, MethodCallHandler {
    private lateinit var channel: MethodChannel
    private lateinit var context: Context
    private var vpnService: LocalVpnService? = null

    companion object {
        const val CHANNEL_NAME = "com.fimuer.vpn/core"
        const val VPN_REQUEST_CODE = 1001
    }

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        context = binding.applicationContext
        channel = MethodChannel(binding.binaryMessenger, CHANNEL_NAME)
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        when (call.method) {
            "startXray" -> {
                val config = call.argument<String>("config")
                if (config != null) {
                    startXray(config, result)
                } else {
                    result.error("INVALID_ARGUMENT", "Config is required", null)
                }
            }
            "stopXray" -> {
                stopXray(result)
            }
            "getTrafficStats" -> {
                getTrafficStats(result)
            }
            "prepareVpn" -> {
                prepareVpn(result)
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    /**
     * 准备 VPN 服务（请求用户授权）
     */
    private fun prepareVpn(result: Result) {
        val intent = VpnService.prepare(context)
        if (intent != null) {
            // 需要用户授权，返回 false
            // Flutter 层应该显示授权对话框
            result.success(false)
        } else {
            // 已授权
            result.success(true)
        }
    }

    /**
     * 启动 Xray 核心
     */
    private fun startXray(config: String, result: Result) {
        try {
            // 1. 写入配置文件
            val configFile = File(context.filesDir, "xray_config.json")
            FileOutputStream(configFile).use { output ->
                output.write(config.toByteArray(Charset.forName("UTF-8")))
            }

            // 2. 启动 VPN 服务
            val intent = Intent(context, LocalVpnService::class.java).apply {
                putExtra("config_path", configFile.absolutePath)
                action = LocalVpnService.ACTION_START
            }
            
            context.startService(intent)
            
            result.success(true)
        } catch (e: Exception) {
            result.error("START_FAILED", "Failed to start Xray: ${e.message}", null)
        }
    }

    /**
     * 停止 Xray 核心
     */
    private fun stopXray(result: Result) {
        try {
            val intent = Intent(context, LocalVpnService::class.java).apply {
                action = LocalVpnService.ACTION_STOP
            }
            context.startService(intent)
            result.success(true)
        } catch (e: Exception) {
            result.error("STOP_FAILED", "Failed to stop Xray: ${e.message}", null)
        }
    }

    /**
     * 获取流量统计
     */
    private fun getTrafficStats(result: Result) {
        try {
            // 从 VPN 服务获取流量统计
            val stats = mapOf(
                "uploadSpeed" to 0,
                "downloadSpeed" to 0,
                "totalUpload" to 0,
                "totalDownload" to 0
            )
            result.success(stats)
        } catch (e: Exception) {
            result.error("STATS_FAILED", "Failed to get traffic stats: ${e.message}", null)
        }
    }
}

/**
 * VPN 服务实现
 * 实际创建 VPN 隧道并路由流量
 */
class LocalVpnService : VpnService() {
    companion object {
        const val ACTION_START = "com.example.flutter_vpn.START"
        const val ACTION_STOP = "com.example.flutter_vpn.STOP"
    }

    private var vpnInterface: ParcelFileDescriptor? = null
    private var xrayProcess: Process? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            ACTION_START -> {
                val configPath = intent.getStringExtra("config_path")
                if (configPath != null) {
                    startVpn(configPath)
                }
            }
            ACTION_STOP -> {
                stopVpn()
            }
        }
        return START_STICKY
    }

    /**
     * 启动 VPN
     */
    private fun startVpn(configPath: String) {
        try {
            // 1. 创建 VPN 接口
            val builder = Builder()
                .setSession("Fimuer VPN")
                .addAddress("10.0.0.2", 24) // VPN 虚拟地址
                .addRoute("0.0.0.0", 0) // 路由所有流量
                .addDnsServer("8.8.8.8") // Google DNS
                .addDnsServer("1.1.1.1") // Cloudflare DNS
                .setMtu(1500)
                .setBlocking(false)

            vpnInterface = builder.establish()

            // 2. 启动 Xray 核心（如果已集成）
            // 这里需要实际的 Xray 核心库支持
            // 例如：使用 libxray.so 或通过 JNI 调用
            
            // 3. 处理数据包转发
            // 需要实现数据包读取和写入逻辑
            
            println("VPN started successfully")
        } catch (e: Exception) {
            println("Failed to start VPN: ${e.message}")
            stopVpn()
        }
    }

    /**
     * 停止 VPN
     */
    private fun stopVpn() {
        try {
            // 停止 Xray 进程
            xrayProcess?.destroy()
            xrayProcess = null

            // 关闭 VPN 接口
            vpnInterface?.close()
            vpnInterface = null

            println("VPN stopped successfully")
        } catch (e: Exception) {
            println("Failed to stop VPN: ${e.message}")
        } finally {
            stopSelf()
        }
    }

    override fun onDestroy() {
        stopVpn()
        super.onDestroy()
    }
}
